package com.situ.stl.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.stl.Service.CoachService;
import com.situ.stl.model.Coach;
import com.situ.stl.util.JsonResult;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/coach")
public class CoachApi {
    private CoachService coachService;

    @Autowired
    public void setCoachService(CoachService coachService) {
        this.coachService = coachService;
    }

//    配置文件获取服务器端口
    @Value("${server.port:8080}")
    private String serverPort;

    private void buildFullImageUrl(Coach coach) {
        String serverBaseUrl = "http://localhost:8080";
        if (coach.getPhoto() != null && ! coach.getPhoto().startsWith("http")) {
            coach.setPhoto(serverBaseUrl + coach.getPhoto());
        }
     }



    // 1. 查询教练（支持分页+姓名/手机号条件）
    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(
            @RequestParam(defaultValue = "1")
            @Min(value = 1, message = "页码不能小于1")
            Integer pageNo,
            @RequestParam(defaultValue = "10")
            @Min(value = 1, message = "每页条数不能小于1")
            @Max(value = 100, message = "每页条数不能超过100")
            Integer pageSize,
            // 新增：接收姓名和手机号查询条件（非必填）
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone
    ) {
        // 构建查询条件对象
        Coach queryCoach = new Coach();
        queryCoach.setName(name);
        queryCoach.setPhone(phone);

        // 分页查询
        Page<Coach> page = new Page<>(pageNo, pageSize);
        page = this.coachService.findAll(page, queryCoach);
        return ResponseEntity.ok(JsonResult.success(page));
    }





    //根据单个id查询教练
    @GetMapping("/{ids}")
    public ResponseEntity<JsonResult<?>> getByIds(
            @PathVariable
            @Min(value = 1, message = "ID必须为正整数")
            Integer ids
    ) {
        Coach coach = coachService.getByIds(ids);

        if (coach == null) {
            return ResponseEntity.ok(JsonResult.fail("教练不存在"));
        } else {
            return ResponseEntity.ok(JsonResult.success(coach));
        }
    }

    // 3. 创建新教练
    @PostMapping
    public ResponseEntity<JsonResult<?>> addCoach(
            @Valid @RequestBody Coach coach  // @Valid启用参数校验（对应Coach类的注解）
    ) {
        boolean success = coachService.save(coach);
        if (success) {
            //            处理成功返回图片
            buildFullImageUrl(coach);

            return ResponseEntity.ok(JsonResult.success("教练创建成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("教练创建失败"));
        }
    }

    // 4. 编辑教练信息
    @PutMapping
    public ResponseEntity<JsonResult<?>> editCoach(
            @Valid @RequestBody Coach coach
    ) {

        // 校验ID是否存在
        if (coach.getId() == null || coachService.getByIds(coach.getId()) == null) {
            return ResponseEntity.ok(JsonResult.fail("教练ID不存在"));
        }
        boolean success = coachService.update(coach);
        if (success) {
//            处理成功返回图片
            buildFullImageUrl(coach);

            return ResponseEntity.ok(JsonResult.success("教练编辑成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("教练编辑失败"));
        }
    }

    // 5. 删除教练（单个ID）
    @DeleteMapping("/{id}")
    public ResponseEntity<JsonResult<?>> deleteCoach(
            @PathVariable
            @Min(value = 1, message = "ID必须为正整数")
            Integer id
    ) {
        boolean success = coachService.removeById(id);  // 新增的Service方法
        if (success) {
            return ResponseEntity.ok(JsonResult.success("教练删除成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("教练删除失败或ID不存在"));
        }
    }

    // 新增：处理参数校验异常（如姓名为空、手机号格式错误）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<JsonResult<?>> handleValidException(MethodArgumentNotValidException e) {
        // 获取校验失败的错误信息
        String errorMsg = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseEntity.ok(JsonResult.fail(errorMsg));
    }
}
